#include "mqttClient.h"
#include <iostream>

MqttClient::MqttClient(const std::vector<std::string>& topics) 
    : client_(SERVER_ADDRESS, CLIENT_ID), running_(true), topics_(topics) {
    
    // 设置连接选项
    connOpts_.set_keep_alive_interval(20);
    connOpts_.set_clean_session(true);
    
    // 设置回调（关键步骤：将当前对象注册为回调处理器）
    client_.set_callback(*this);
}

MqttClient::~MqttClient() {
    stop();
}

void MqttClient::start() {
    try {
        // 连接到MQTT代理
        std::cout << "Connecting to the MQTT server..." << std::endl;
        mqtt::token_ptr conntok = client_.connect(connOpts_);
        conntok->wait();
        std::cout << "Connected!" << std::endl;
        
        // 订阅主题
        std::cout << "Subscribing to topics... ";
        for (const auto& topic : topics_) {
            std::cout << topic << " ";
            client_.subscribe(topic, QOS)->wait();
        }
        std::cout << std::endl;
        
        // 启动发布线程
        publishThread_ = std::thread(&MqttClient::publishLoop, this);
    }
    catch (const mqtt::exception& exc) {
        std::cerr << "MQTT error: " << exc.what() << std::endl;
    }
}

void MqttClient::stop() {
    if (!running_) return;
    
    running_ = false;
    queueCondVar_.notify_all();
    
    if (publishThread_.joinable()) {
        publishThread_.join();
    }
    
    try {
        // 取消订阅
        for (const auto& topic : topics_) {
            client_.unsubscribe(topic)->wait();
        }
        
        // 断开连接
        std::cout << "Disconnecting..." << std::endl;
        client_.disconnect()->wait();
        std::cout << "Disconnected!" << std::endl;
    }
    catch (const mqtt::exception& exc) {
        std::cerr << "MQTT error during disconnect: " << exc.what() << std::endl;
    }
}

void MqttClient::enqueueMessage(const std::string& topic, const std::string& payload) {
    std::lock_guard<std::mutex> lock(queueMutex_);
    messageQueue_.push({topic, payload});
    queueCondVar_.notify_one();
}

void MqttClient::handleMessage(const std::string& topic, const std::string& payload) {
    std::cout << "收到订阅消息 - 主题: " << topic << ", 内容: " << payload << std::endl;
    // 在这里添加您的消息处理逻辑
}

void MqttClient::publishLoop() {
    while (running_) {
        Message msg;
        
        // 等待队列中有消息
        {
            std::unique_lock<std::mutex> lock(queueMutex_);
            queueCondVar_.wait(lock, [this]{ return !messageQueue_.empty() || !running_; });
            
            if (!running_) break;
            
            msg = std::move(messageQueue_.front());
            messageQueue_.pop();
        }
        
        try {
            // 发布消息
            mqtt::message_ptr pubmsg = mqtt::make_message(msg.topic, msg.payload);
            pubmsg->set_qos(QOS);
            client_.publish(pubmsg)->wait();
           // std::cout << "已发布消息 - 主题: " << msg.topic << ", 内容: " << msg.payload << std::endl;
        }
        catch (const mqtt::exception& exc) {
            std::cerr << "发布消息失败: " << exc.what() << std::endl;
        }
    }
}

void MqttClient::message_arrived(mqtt::const_message_ptr msg) {
    std::string topic = msg->get_topic();
    std::string payload = msg->to_string();
    
    // 调用用户自定义的消息处理函数
    handleMessage(topic, payload);
}

void MqttClient::connection_lost(const std::string& cause) {
    std::cout << "连接丢失，原因: " << cause << std::endl;
    // 可在此添加重连逻辑
}

void MqttClient::delivery_complete(mqtt::delivery_token_ptr token) {
    if (token) {
        std::cout << "消息发布完成，ID: " << token->get_message_id() << std::endl;
    }
}